<?php

	require_once(dirname(__FILE__)."/../core/safeParam.php");
	
	function get_activation_time($userid){
		global $database;
		$result = $database->selectFirst( "select activation_time from users where id= '$userid'");
		return $activation_time = strtotime($result['activation_time']);	
	}
	
	function checkPassword($email, $password){
		global $database;

		$return_value= array('id'=>0,'resetflag'=>FALSE,'valid_login'=>FALSE);
		$hashedPassword = md5($password);
		$result= $database->selectFirst("select id from users where email = '$email' and password = '$hashedPassword'");
		
		if (!$result ) {
			return $return_value;
		}
		
		$return_value['id'] = $result['id'];
		$return_value['valid_login'] = TRUE;
		$activation_time = get_activation_time($return_value['id']);
		
		if($activation_time==NULL){
			return $return_value;
		}
		
		$current_time= strtotime(date('Y-m-d H:i:s'));
		
		if($activation_time>= $current_time){
			//reset time to null
			$userid=$result['id'];
			$update_value = "activation_time='NULL'";
			$condition = "id = '$userid'";
			$update = $database->update("users", $update_value, $condition);
			$return_value['resetflag']= TRUE; 
		}
		
		return $return_value;
	}
	
	function redirect($url){
		echo makeRedirect($url);
	}
	
	function makeRedirect($url){
		return '
		<script type="text/javascript">
			window.location = $url
  		</script>';
	}
	
	function updateOption($name, $data, $id){
  		global $database;
  		
  		$insert['value'] = $data;
		
		$database->update_array("options", $insert, "id = '$id'");
	}

	function addOption($name, $data, $rid = NULL){
		global $database;
  		$insert['name']  = $name;
  		$insert['value'] = $data;
  		$insert['rid']   = $rid;
  		$database->insert_array("options", $insert);
	}

	function getOption($name, $rid = NULL, $unique = FALSE, $array = FALSE){
  		global $database;
  		
  		if ($rid != NULL) {
    		$extra = " and rid = '" . $rid . "' ";
  		} else {
    		$extra = "  ";
  		}
  		
  		if ($unique == FALSE) {
    		$un = " GROUP BY value ";
  		} else {
    		$un = " ";
  		}
  		
  		$results = $database->select("SELECT * from options where name = '$name' " . $extra . " " . $un . " order by value");
  		
  		if (count($results) > 1 or $array != FALSE) {
    		return $results;
  		} else {
    		$val = $results[0]['value'];
    		
    		if (! is_serialized($val)){
    			return $val;
    		} else {
      		$data = @unserialize($val);
      		
      		if ($data !== false) {
        			return $data;
      		} 
      		
      		return $val;
    		}
  		}
	}

function is_serialized($value, &$result = null){ 
// Bit of a give away this one
  if ( ! is_string( $value ) ) {
    return FALSE;
  }

  // Serialized FALSE, return TRUE. unserialize() returns FALSE on an
  // invalid string or it could return FALSE if the string is serialized
  // FALSE, eliminate that possibility.
  if ( 'b:0;' === $value ) {
    $result = FALSE;
    return TRUE;
  }

  $length       = strlen($value);
  $end  = '';

  if ( isset( $value[0] ) ) {
    switch ($value[0]) {
      case 's':
        if ( '"' !== $value[$length - 2] )
          return FALSE;

      case 'b':
      case 'i':
      case 'd':
        // This looks odd but it is quicker than isset()ing
        $end .= ';';
      case 'a':
      case 'O':
        $end .= '}';

        if ( ':' !== $value[1] )
          return FALSE;

        switch ( $value[2] ) {
          case 0:
          case 1:
          case 2:
          case 3:
          case 4:
          case 5:
          case 6:
          case 7:
          case 8:
          case 9:
          break;

          default:
            return FALSE;
        }
      case 'N':
        $end .= ';';

        if ( $value[$length - 1] !== $end[0] )
          return FALSE;
      break;

      default:
        return FALSE;
    }
  }

  if ( ( $result = @unserialize($value) ) === FALSE ) {
    $result = null;
    return FALSE;
  }

  return TRUE;
} 

	function testMail($text){
  		//send mail
  		$m = new Mail; // create the mail
  		$m->From(ADMIN_EMAIL);
  		$m->To(ADMIN_EMAIL);
  		$m->Subject('Test mail');
  		$m->Body($text); // set the body	
  		$m->Send(); // send the mail
	}
		
	function completeOrder($cart_order_id, $extra = false, $return_online = false){
  		global $database, $lang, $config;
  		
  		$content .= $extra;
  		$results          = $database->select("SELECT * FROM order_sum WHERE id = " . $cart_order_id . " ");
  		$results_user     = $database->select("SELECT * FROM users where id = " . $results[0]['uid'] . " ");
  		$results_location = $database->select("SELECT * FROM locations where id = " . $results[0]['lid'] . " ");
  		$results_inv      = $database->select("SELECT * FROM order_inv where oid = " . $results[0]['id'] . " ");
  		
  		if ($results[0]['delivery'] == "Yes") {
    		$delivery_add = '
    		<h4>Delivery Address</h4>
      	' . $results[0]['delivery_address1'] . '  ' . stripslashes($results[0]['delivery_address2']) . '

      	<br />

      	' . $results[0]['delivery_city'] . ' ';
  		}
  		
  		$total = $_SESSION['final'];
  		$content .= '
  		<div id="printme">
  			<h4>' . $lang['order_info'] . '</h4>
  			<table cellspacing="0" cellpadding="2" border="0" class="table_form" style="text-align:left">
  				<tr>
  					<td>' . $lang['cn'] . '</td>
  					
  					<td>
  						<a href="index.php?edit=users&lid=' . $results_user[0]['id'] . '">' . $results_user[0]['name'] . '   ' . $results_user[0]['last_name'] . '</a>
  					</td>
  				</tr>
  				
  				<tr>
  					<td>' . $lang['phone'] . ':</td>
  					<td>' . $results_user[0]['phone'] . ' </td>
  				</tr>
  				
  				<tr>
  					<td>' . $lang['order_date'] . ':</td>
  					<td> ' . date("F d Y h:i: A", strtotime($results[0]['date'])) . ' </td>
  				</tr>
  				
  				<tr style="background-color:CCC">
  					<td>' . $lang['order_total'] . ':</td>
  					<td>' . @money_format('%i', $total) . '</td>
  				</tr>
  				
  				<tr>
  					<td>' . $lang['delivery'] . ':</td>
  					<td> ' . $results[0]['delivery'] . ' </td>
  				</tr>
  				
  				<tr style="background-color:CCC">
  					<td>' . $lang['payment'] . ':</td>
  					<td>' . $results[0]['payment'] . '</td>
  				</tr>
            
            ' . $coupon . '
            <tr>
            	<td colspan="2" style="background-color:#CCC;color:#FFF;font-size:1.4em;font-weight:bold">' . $lang['customer_info'] . '</td>
            </tr>
            
            <tr>
            	<td>
            		<h4>' . $lang['billing_address'] . '</h4>
            		' . $results[0]['address1'] . '  ' . stripslashes($results[0]['address2']) . '
            		
            		<br />
            		
            		' . $results[0]['city'] . ',	' . stripslashes($results[0]['state']) . '	' . stripslashes($results[0]['zip']) . '			
            	</td>
            	
            	<td> ' . $delivery_add . ' </td>
            </tr>
            
            <tr style="background-color:CCC">
            	<td>' . $lang['comments'] . ':</td>
            	<td>' . $results[0]['comments'] . '</td>
            </tr>
            
            <tr>
            	<td colspan="2" style="background-color:#CCC;color:#FFF;font-size:1.4em;font-weight:bold">' . $lang['order_details'] . '</td>
            </tr>
            
            <tr>
            	<tr>
            		<td  colspan="3">
            			<table width="100%" border="0" cellspacing="3" cellpadding="3">';
            				for ($i = 0; $i < count($results_inv); $i++) {
            					if ($results_inv[$i]['file'] != "") {
            						$attach_files = '
            						<br />
            						
            						<strong>Attachment: </strong>
            						<a href="http://' . $_SERVER["SERVER_NAME"] . '/UserFiles/File/customers/' . $results_inv[$i]['file'] . '">
      									Click here to download
      								</a>
      								
      								<br />';
									} else {
										$attach_files = '';
    								}
    								
    								$price = $results_inv[$i]['item_price'] * $results_inv[$i]['item_quantity'];
    								
    								$content .= '
    								<tr>
    									<td style="border:none" width="400">
    										<b> ' . $results_inv[$i]['item_quantity'] . ' x ' . $lang['item'] . ':</b>  '. $results_inv[$i]['item_name'] . ' 
    									</td>
    									
    									<td  style="border:none">
    										<b>' . $lang['price'] . ':</b>  ' . price_format($results_inv[$i]['item_price']) . ' 
    										<b style="margin-left:120px">' . $lang['total'] . ':</b>  ' . price_format($price) . '
    									</td>
    								</tr>
    								
    								<tr>
    									<td colspan="2" style="border-bottom:1px dotted #CCC;padding-bottom:10px">
    										' . html_entity_decode( $results_inv[$i]['item_description']) . '
    										' . $attach_files . '
    									</td>
    								</tr>';
  								} 
  								
  								$content .= '
  								</table>
  									<div style="text-align:right">
  										<h3>
  											' . $lang['subtotal'] . ':' . price_format($results[0]['subtotal']) . '
  										
  											<br />
	        							
	        								' . $lang['tip'] . ': ' . price_format($results[0]['tips']) . '
	        							
	        								<br />
	        							
	        								' . $lang['tax'] . ': ' . price_format($results[0]['tax']) . '
	        							
	        								<br />
	        							
	        								' . $lang['delivery_fee'] . ': ' . price_format($results[0]['delivery_fee']) . '
	        							
	        								<br />
	        							
	        								' . $lang['coupon'] . ': - ' . price_format($_SESSION['discount']) . '
	        							
	        								<br />
	        							
	        								<span>
	        									' . $lang['total'] . ':   ' . price_format($total) . '
	        								</span>
        								</h3>
        							</div>
        						</td>
                        </tr>
                        </tr>
                        </table>
        						</div>';
        						
      if ($return_online == true) {
      	return $content;
  		} else {
  			if ($config['smtp_server'] != "") {
  				
  				require_once('smtp.mail.php');
  										
  				$headers = "Content-Transfer-Encoding: 8bit\r\n";
      		$headers .= 'Content-Type: text/html; charset="iso-8859-1"' . "\r\n";
      		$to       = $results_location[0]['email'];
      		$from     = $results_user[0]['email'];      								
      		
      		$subject  = "" . $config['sitename'] . " New order #" . $cart_order_id . " " . $results_user[0]['firstName'] . " " . $results_user[0]['lastName'] . "";
      								
      		$body     = '' . $_SESSION['customer_info'] . '<br><br>' . $content . '';
      								
      		$SMTPMail = new SMTPClient($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body, $headers);
      		$SMTPChat = $SMTPMail->SendMail();
      		$to       = $results_user[0]['email'];
      		$from     = $results_location[0]['email'];
      		$subject  = "" . SITE_NAME . " - " . $lang['order'] . " #" . $cart_order_id . "";
      		$body     = '<h1>' . $lang['order'] . ' #' . $cart_order_id . '</h1><p>' . sprintf($lang['thankyou_email'], $results[0]['time_ready'], $content) . '';
      		$SMTPMail = new SMTPClient($SmtpServer, $SmtpPort, $SmtpUser, $SmtpPass, $from, $to, $subject, $body, $headers);
      		$SMTPChat = $SMTPMail->SendMail();
    		} else {
    			//send mail
      		$admineMail = new Mail; // create the mail
      		$admineMail ->From($results_user[0]['email']);
      		$admineMail ->To($results_location[0]['email']);
      		$admineMail ->Cc(ADMIN_EMAIL);
      		$admineMail ->Subject("" . $config['sitename'] . " New order #" . $cart_order_id . " " . $results_user[0]['firstName'] . " " . $results_user[0]['lastName'] . "");
      		$admineMail ->Body('' . $_SESSION['customer_info'] . '<br><br>' . $content . ''); // set the body	
      		$admineMail ->Send(); // send the mail
      											
      		//send mail
      		$usereMail = new Mail; // create the mail
      		$usereMail ->From($results_location[0]['email']);
      		$usereMail ->To($results_user[0]['email']);
      		$usereMail ->Subject("" . SITE_NAME . " - " . $lang['order'] . " #" . $cart_order_id . "");
      		$usereMail ->Body('<h1>' . $lang['order'] . ' #' . $cart_order_id . '</h1><p>' . sprintf($lang['thankyou_email'], $results[0]['time_ready'], $content) . ''); // set the body	
      		$usereMail ->Send(); // send the mail	
    		}
    	}
    	
    	$up['status'] = 1;
  		$update       = $database->update_array("order_sum", $up, "id=$cart_order_id");
  		
  		return $content;
  	}
	
	function xml2array($contents, $get_attributes = 1, $priority = 'tag')
{
  if (!$contents)
    return array();
  if (!function_exists('xml_parser_create')) {
    //print "'xml_parser_create()' function not found!";
    return array();
  } //!function_exists('xml_parser_create')
  //Get the XML parser of PHP - PHP must have this module for the parser to work
  $parser = xml_parser_create('');
  xml_parser_set_option($parser, XML_OPTION_TARGET_ENCODING, "UTF-8"); # http://minutillo.com/steve/weblog/2004/6/17/php-xml-and-character-encodings-a-tale-of-sadness-rage-and-data-loss
  xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
  xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, 1);
  xml_parse_into_struct($parser, trim($contents), $xml_values);
  xml_parser_free($parser);
  if (!$xml_values)
    return; //Hmm...
  //Initializations
  $xml_array   = array();
  $parents     = array();
  $opened_tags = array();
  $arr         = array();
  $current =& $xml_array; //Refference
  //Go through the tags.
  $repeated_tag_index = array(); //Multiple tags with same name will be turned into an array
  foreach ($xml_values as $data) {
    unset($attributes, $value); //Remove existing values, or there will be trouble
    //This command will extract these variables into the foreach scope
    // tag(string), type(string), level(int), attributes(array).
    extract($data); //We could use the array by itself, but this cooler.
    $result          = array();
    $attributes_data = array();
    if (isset($value)) {
      if ($priority == 'tag')
        $result = $value;
      else
        $result['value'] = $value; //Put the value in a assoc array if we are in the 'Attribute' mode
    } //isset($value)
    //Set the attributes too.
    if (isset($attributes) and $get_attributes) {
      foreach ($attributes as $attr => $val) {
        if ($priority == 'tag')
          $attributes_data[$attr] = $val;
        else
          $result['attr'][$attr] = $val; //Set all the attributes in a array called 'attr'
      } //$attributes as $attr => $val
    } //isset($attributes) and $get_attributes
    //See tag status and do the needed.
    if ($type == "open") { //The starting of the tag '<tag>'
      $parent[$level - 1] =& $current;
      if (!is_array($current) or (!in_array($tag, array_keys($current)))) { //Insert New tag
        $current[$tag] = $result;
        if ($attributes_data)
          $current[$tag . '_attr'] = $attributes_data;
        $repeated_tag_index[$tag . '_' . $level] = 1;
        $current =& $current[$tag];
      } //!is_array($current) or (!in_array($tag, array_keys($current)))
      else { //There was another element with the same tag name
        if (isset($current[$tag][0])) { //If there is a 0th element it is already an array
          $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
          $repeated_tag_index[$tag . '_' . $level]++;
        } //isset($current[$tag][0])
        else { //This section will make the value an array if multiple tags with the same name appear together
          $current[$tag]                           = array(
            $current[$tag],
            $result
          ); //This will combine the existing item and the new item together to make an array
          $repeated_tag_index[$tag . '_' . $level] = 2;
          if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well
            $current[$tag]['0_attr'] = $current[$tag . '_attr'];
            unset($current[$tag . '_attr']);
          } //isset($current[$tag . '_attr'])
        }
        $last_item_index = $repeated_tag_index[$tag . '_' . $level] - 1;
        $current =& $current[$tag][$last_item_index];
      }
    } //$type == "open"
    elseif ($type == "complete") { //Tags that ends in 1 line '<tag />'
      //See if the key is already taken.
      if (!isset($current[$tag])) { //New Key
        $current[$tag]                           = $result;
        $repeated_tag_index[$tag . '_' . $level] = 1;
        if ($priority == 'tag' and $attributes_data)
          $current[$tag . '_attr'] = $attributes_data;
      } //!isset($current[$tag])
      else { //If taken, put all things inside a list(array)
        if (isset($current[$tag][0]) and is_array($current[$tag])) { //If it is already an array...
          // ...push the new element into that array.
          $current[$tag][$repeated_tag_index[$tag . '_' . $level]] = $result;
          if ($priority == 'tag' and $get_attributes and $attributes_data) {
            $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
          } //$priority == 'tag' and $get_attributes and $attributes_data
          $repeated_tag_index[$tag . '_' . $level]++;
        } //isset($current[$tag][0]) and is_array($current[$tag])
        else { //If it is not an array...
          $current[$tag]                           = array(
            $current[$tag],
            $result
          ); //...Make it an array using using the existing value and the new value
          $repeated_tag_index[$tag . '_' . $level] = 1;
          if ($priority == 'tag' and $get_attributes) {
            if (isset($current[$tag . '_attr'])) { //The attribute of the last(0th) tag must be moved as well
              $current[$tag]['0_attr'] = $current[$tag . '_attr'];
              unset($current[$tag . '_attr']);
            } //isset($current[$tag . '_attr'])
            if ($attributes_data) {
              $current[$tag][$repeated_tag_index[$tag . '_' . $level] . '_attr'] = $attributes_data;
            } //$attributes_data
          } //$priority == 'tag' and $get_attributes
          $repeated_tag_index[$tag . '_' . $level]++; //0 and 1 index is already taken
        }
      }
    } //$type == "complete"
      elseif ($type == 'close') { //End of tag '</tag>'
      $current =& $parent[$level - 1];
    } //$type == 'close'
  } //$xml_values as $data
  return ($xml_array);
}
function getGatewayInfo($gateway)
{
  global $database;
  if ($_SESSION['arid'] == "") {
    $arid = $_SESSION['frid'];
  } //$_SESSION['arid'] == ""
  else {
    $arid = $_SESSION['arid'];
  }
  $results = $database->select("SELECT * from gateway where name = '" . $gateway . "' and rid = " . $arid . "");
  return $results[0];
}
function getGateway($gateway)
{
  global $database;
  if ($_SESSION['arid'] == "") {
    $arid = $_SESSION['frid'];
  } //$_SESSION['arid'] == ""
  else {
    $arid = $_SESSION['arid'];
  }
  $results = $database->select("SELECT * from gateway where name = '" . $gateway . "' and rid = " . $arid . "");
  return unserialize($results[0]['options']);
}
function csvstring_to_array($string, $separatorChar = ',', $enclosureChar = '"', $newlineChar = "\n")
{
  // @author: Klemen Nagode
  $array        = array();
  $size         = strlen($string);
  $columnIndex  = 0;
  $rowIndex     = 0;
  $fieldValue   = "";
  $isEnclosured = false;
  for ($i = 0; $i < $size; $i++) {
    $char    = $string{$i};
    $addChar = "";
    if ($isEnclosured) {
      if ($char == $enclosureChar) {
        if ($i + 1 < $size && $string{$i + 1} == $enclosureChar) {
          // escaped char
          $addChar = $char;
          $i++; // dont check next char
        } //$i + 1 < $size && $string{$i + 1} == $enclosureChar
        else {
          $isEnclosured = false;
        }
      } //$char == $enclosureChar
      else {
        $addChar = $char;
      }
    } //$isEnclosured
    else {
      if ($char == $enclosureChar) {
        $isEnclosured = true;
      } //$char == $enclosureChar
      else {
        if ($char == $separatorChar) {
          $array[$rowIndex][$columnIndex] = $fieldValue;
          $fieldValue                     = "";
          $columnIndex++;
        } //$char == $separatorChar
        elseif ($char == $newlineChar) {
          echo $char;
          $array[$rowIndex][$columnIndex] = $fieldValue;
          $fieldValue                     = "";
          $columnIndex                    = 0;
          $rowIndex++;
        } //$char == $newlineChar
        else {
          $addChar = $char;
        }
      }
    }
    if ($addChar != "") {
      $fieldValue .= $addChar;
    } //$addChar != ""
  } //$i = 0; $i < $size; $i++
  if ($fieldValue) { // save last field
    $array[$rowIndex][$columnIndex] = $fieldValue;
  } //$fieldValue
  return $array;
}
function getTitle($url)
{
  $fh  = fopen($url, "r");
  $str = fread($fh, 7500); // read the first 7500 characters, it's gonna be near the top
  fclose($fh);
  $str2  = strtolower($str);
  $start = strpos($str2, "<title>") + 7;
  $len   = strpos($str2, "</title>") - $start;
  return substr($str, $start, $len);
}
function curPageURL()
{
  $pageURL = 'http';
  if (isset($_SERVER["HTTPS"]) && $_SERVER["HTTPS"] == "on") {
    $pageURL .= "s";
  } //$_SERVER["HTTPS"] == "on"
  $pageURL .= "://";
  if ($_SERVER["SERVER_PORT"] != "80") {
    $pageURL .= $_SERVER["SERVER_NAME"] . ":" . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
  } //$_SERVER["SERVER_PORT"] != "80"
  else {
    $pageURL .= $_SERVER["SERVER_NAME"] . $_SERVER["REQUEST_URI"];
  }
  return $pageURL;
}

	function trackPage(){
		global $database;
	
		if (isset($_SERVER['HTTP_X_FORWARD_FOR']) && $_SERVER['HTTP_X_FORWARD_FOR'] != "") {
			$ip = $_SERVER['HTTP_X_FORWARD_FOR'];
		} else {
			$ip = $_SERVER['REMOTE_ADDR'];
		}
	
		if (isset($_SESSION['userid']) && $_SERVER["userid"] != "") {
			$data['user'] = $_SESSION['userid'];
		} //$_SESSION['userid'] != ""
	
		$data['rid']  = RID;
  		$data['ip']   = $ip;
  		$data['page'] = curPageURL();
  		$data['date'] = date("Y-m-d");
  		$visits       = $database->select("SELECT * from tracker where ip = '" . $ip . "' AND page = '" . $data['page'] . "'");
  	
  		if ($visits == FALSE) {
  			$database->insert_array('tracker', $data);
  		} else {
  			$data['visits'] = $visits[0]['visits'] + 1;
  			$database->update_array('tracker', $data, "id = " . $visits[0]['id'] . "");
  		}
	}

	function uploadImage($files, $width, $height, $folder, $field, $filenameToUse = ""){
		$file['tmp']   = $files[$field]['tmp_name'];
  		$file['type']  = $files[$field]['type'];
  		$file['size']  = $files[$field]['size'];
  		
  		$allowed_types = array(
  			'image/jpeg',
    		'image/pjpeg',
    		'image/gif',
    		'image/png',
    		'image/bmp'
  		);
  		
  		if ($file['tmp'] != "" && is_uploaded_file($file['tmp'])) {
  			if (!in_array($file['type'], $allowed_types)) {
  				echo 'Error!';
  				exit();
    		} //!in_array($file['type'], $allowed_types)
    		
    		if ($file['size'] == 0) {
    			echo 'Error!';
    			exit();
    		} //$file['size'] == 0
    		
    		switch ($file['type']) {
    			case 'image/gif';
        			$ext = "gif";
        		break;
      		
      		case 'image/jpeg';
        			$ext = "jpg";
        		break;
      		
      		case 'image/pjpeg';
        			$ext = "jpg";
        		break;
      		
      		case 'image/png';
        			$ext = "png";
        		break;
      		
      		case 'image/bmp';
        			$ext = "bmp";
        		break;
    		} //$file['type']
    		
    		srand(time());
    		
    		if (!$filenameToUse) {
      		$rander        = (rand() % 1040645645600);
      		$filename      = (rand() % 100000000000) . $rander;
      		$photo         = $filename . "." . $files[$field]['name'];
    		} else {
      		$photo         = $filenameToUse;
    		}
    		
    		$uploaded_file = '' . $folder . '' . $photo;
    		$rimg          = new RESIZEIMAGE($file['tmp']);
    		$rimg->resize_limitwh($width, $height, $uploaded_file);
    		$rimg->close();
  		} //$file['tmp'] != "" && is_uploaded_file($file['tmp'])
  		
  		return $photo;
	}

function createRandomPassword()
{
  $chars = "abcdefghijkmnopqrstuvwxyz023456789";
  srand((double) microtime() * 1000000);
  $i    = 0;
  $pass = '';
  while ($i <= 7) {
    $num  = rand() % 33;
    $tmp  = substr($chars, $num, 1);
    $pass = $pass . $tmp;
    $i++;
  } //$i <= 7
  return $pass;
}
function userArray($id)
{
  global $database;
  $results = $database->select("SELECT * FROM users where id = $id");
  return $results[0];
}
function locationArray($id)
{
  global $database;
  $results = $database->select("SELECT * FROM locations where id = $id");
  return $results;
}

	function locationBoxID($id){
		global $database;
		$results  = $database->select("SELECT * FROM locations where id = $id");
  		$results2 = $database->select("SELECT * FROM locations WHERE rid = " . RID . " ");
  		
  		if (count($results2) == 1 && $results2[0]['id'] != "") {
    		return false;
  		} else {
    		$box .= '
    		<div id="choose_location">
    			<table width="100%" border="1" cellspacing="3" cellpadding="3">
  					<tr>
    					<th colspan="2">
    						<div class="location_header">
    							Ordering Location: ' . $results[0]['name'] . '
    						</div>
    						</h2>
    					</th>
    				</tr>
  					
  					<tr>
    					<th>';
    		
    		if ($results[0]['phone'] != '') {
    			$box .= 'Phone:' . $results[0]['phone'] . '<br>';
    		} 
    		
    		if ($results[0]['address'] != '') {
      		$box .= '' . $results[0]['address'] . '
      		<br>
      		' . $results[0]['city'] . ', ' . $results[0]['state'] . '  
      		<a target="_blank" href="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=' . $results[0]['address'] . '+' . $results[0]['city'] . '+' . $results[0]['state'] . '&ie=UTF8&hq=&hnear=' . $results[0]['address'] . '+' . $results[0]['city'] . '+' . $results[0]['state'] . '&iwloc=A&iwstate1=dir">(view map)</a> ';
    		}
    		
    		if (getOption('cb-choose-location', RID) == 1) {
      		$box .= '
      		<th>
      			<p class="location_button">
      				<a href="index.php?act=checkout&location=unset">Elegir una nueva Ubicación</a>
      			</p>
      		</th>';
    		} 
    		
    		$box .= '
  					</tr>
				</table>
			</div>';
    		
    		return $box;
  		}
	}

	function locationBox()
{
  global $database;
  $results = $database->select("SELECT * FROM locations WHERE rid = " . RID . " ");
  if (count($results) == 1 && $results[0]['id'] != "") {
    header('Location: index.php?act=checkout&location=' . $results[0]['id'] . '');
  } //count($results) == 1 && $results[0]['id'] != ""
  for ($i = 0; $i < count($results); $i++) {
    $options .= '<table width="100%" border="0" cellspacing="3" cellpadding="3">
  <tr>
    <th colspan="2"><div class="location_header">' . $results[$i]['name'] . '</div></th>
   
  </tr>
  <tr>
    <th>';
    if ($results[$i]['phone'] != '') {
      $options .= 'Phone:' . $results[$i]['phone'] . '<br>';
    } //$results[$i]['phone'] != ''
    if ($results[$i]['fax'] != '') {
      $options .= 'Fax: ' . $results[$i]['fax'] . '<br>';
    } //$results[$i]['fax'] != ''
    if ($results[$i]['address'] != '') {
      $options .= '' . $results[$i]['address'] . '<br>' . $results[$i]['city'] . ', ' . $results[$i]['state'] . '  <a target="_blank" href="http://maps.google.com/maps?f=q&source=s_q&hl=en&geocode=&q=' . $results[$i]['address'] . '+' . $results[$i]['city'] . '+' . $results[$i]['state'] . '&ie=UTF8&hq=&hnear=' . $results[$i]['address'] . '+' . $results[$i]['city'] . '+' . $results[$i]['state'] . '&iwloc=A&iwstate1=dir">(view map)</a> ';
    } //$results[$i]['address'] != ''
    $options .= '<th><p class="location_button"><a href="index.php?act=checkout&location=' . $results[$i]['id'] . '">Seleccionar esta Ubicación</a></p></th>
  </tr>
</table>

		
		
		
		
	';
  } //$i = 0; $i < count($results); $i++
  return '<div id="choose_location">
	' . $options . '</div>';
}
function locationsAmount()
{
  global $database;
  $query = $database->numrows("SELECT * FROM locations  WHERE rid = " . RID . "");
  return $query;
}

function price_format($price)
{
  $moneyConfig = getMoneyConfig();

  if ($price == null) {
    $price = 0;
  }
  $money  = sprintf("%01.2f",$price);

  $symbol = $moneyConfig['money_symbol'];

  if ($moneyConfig['money_position'] == 1) {
    return "$symbol$money";
  } else {
    return "$money$symbol";
  }

}

function getCurrentRestauarantID(){
  if (defined('ARID')) {
    $restaurantID = ARID;
  } //ARID != ""
  else {
    $restaurantID = RID;
  }
  return $restaurantID;
}

	function getMoneyConfig(){
		global $database;
		
		$restaurantID = getCurrentRestauarantID();
		
		static $moneyConfigs;
  		
  		if (isset($moneyConfigs[$restaurantID])){
  			$moneyConfig = $moneyConfigs[$restaurantID];
  		} else {
  			$moneyConfig = $database->selectFirst("select money_position, money_symbol from config where id = '$restaurantID'");
    		$moneyConfigs[$restaurantID] = $moneyConfig;
  		}
  		
  		return $moneyConfig;
	}

	function getMenuProducts($cat_id) {
		global $database;
  		$query = $database->query("SELECT * FROM menu_item where cat = $cat_id");
  		
  		while ($list = mysql_fetch_array($query)) {
  			$id   = $list['id'];
  			$name = $list['name'];
  			$rows .= '
  			<tr>
  				<td align="center" style="border-bottom:1px dashed #52b4e6; padding:5px;">
  					<a href="index.php?edit=menu&item_id=' . $id . '&function=edit-item">
  						'. $name .'
  					</a>
  				</td>
				
				<td align="center" style="border-bottom:1px dashed #52b4e6; padding:5px;">
					<a href="index.php?edit=menu&item_id=' . $id . '&function=edit-item" style="margin-right:10px;">
						<img src="application_edit.png" border="0">
						Editar
					</a>
										
					<a onclick="return confirmDelete(this);"  href="../functions/menus.php?function=delete-item&itemid=' . $id . '&mid=' . $_GET['cat_id'] . '">
						<img src="delete.png" border="0">
						Eliminar
					</a>
				</td>
			</tr>';
  		} //$list = mysql_fetch_array($query)
  		
  		return '
  		<table width="80%"  border="0" cellspacing="0" cellpadding="0" style="margin:auto;">
  			<tr bgcolor="#69E">
  				<td align="center" style="padding:5px;">
          		<b>
          			Nombre del Producto
          		</b>
          	</td>

	 			<td align="center" >
	 				<b>
	 					Funciones
	 				</td>
	 			</td>
	 		</tr>   
	 		
	 		' . $rows . '
	 		
	 	</table>';
}


	function findMenuItems(){
		global $database;
		
		// non assigned
		$query = $database->query("SELECT * FROM menu_cat WHERE rid = ". ARID ." ORDER by pos");
		
		while ($list = mysql_fetch_array($query)) {
			$cat_id          = $list['id'];
			$cat_name        = $list['name'];
    		$cat_description = $list['description'];
    		$cat_pos         = $list['pos'];
    		
    		$rows .= '
    		<tr>
    			<td align="center">
    				<a href="index.php?edit=menu&cat_id=' . $cat_id . '&function=edit-categoria">
    					'. $cat_name .' 
    				</a>
	 			</td>
	 			
	 			<td align="center">
	 				<a href="index.php?edit=menu&cat_id='. $cat_id .'&function=edit-cat">
	 					Editar Productos
	 				</a>
	 				
	 				<b>|</b>
	 				 	 				 
	 				<a href="index.php?edit=menu&cat_id='. $cat_id .'&function=add-item">
	 					Agregar Productos
	 				</a>
	 				
	 				<b>|</b> 
 
	 				<a onclick="return confirmDelete(this);"  href="../functions/menus.php?function=delete-category&catid=' . $cat_id . '&mid=' . $_GET['cat_id'] . '">
	 					Eliminar Categoría
	 				</a>
	 			</td>
	 			
	 			<td align="center">	
					<form class="menuCategory" action="../functions/menus.php?function=order-cats" method="post">
					
						<input name="pos" type="text" size="1" value="' . $cat_pos . '" style="margin-top:10px; width:12px;"> 
						<input name="posid" type="hidden" value="' . $cat_id . '">
					
						<br />
						<br />
						
						<input type="submit" value="Posicionar" />
					</form>
				</td>
			</tr>
			
			<tr>
				<td colspan="3" style="border-bottom: 1px solid #BBB;">
				</td>
			</tr>
			';
    		
    		$row_count++;
  		} //$list = mysql_fetch_array($query)
  		
  		return '
  		<table width="90%"  border="0" cellspacing="0" cellpadding="0" style="margin:auto">
	 		<tr bgcolor="#F0F6F0">
				<td align="center"  style="padding:10px">
					<b>Categorías</b>
				</td>
      			
      		<td align="center" >
      			<b>Funciones</b>
      		</td>
	  				
	  			<td align="center" >
	  				<b>Posición en el Menu</b>
	  			</td>
	 		</tr>
	 		'. $rows .'
  		</table>';
  	}
  	
  	function findPages($type){
  		global $database;
  		
  		// non assigned
  		$query = $database->query("SELECT * FROM pages WHERE parent = 0 AND menu = '$type' AND rid = " . ARID . " ORDER by pos ");
  		
  		while ($list = mysql_fetch_array($query)) {
			$id          = $list['id'];
    		$date        = $list['date'];
    		$title       = $list['title'];
    		$pagename    = $list['pagename'];
    		$linktitle   = $list['linktitle'];
    		$description = $list['description'];
    		$content     = $list['content'];
    		$menuitem    = $list['menuitem'];
    		$hassub      = $list['hassub'];
    		$parent      = $list['parent'];
    		$status      = $list['status'];
    
    		if ($status == '2') {
      		$editlink = 'index.php?edit=pages&function=edit-link&id=' . $id . '';
    		} else {
      		$editlink = 'index.php?edit=pages&id=' . $id . '';
    		}
    		
    		// sub pages list
    		// end sub page slist								
    		$pos = $list['pos'];
    
    		if ($menuitem == '1') {
    			$linktomenu = '<span style="color:green">La página está en el submenu</span>';
      		$csstyle    = 'text-indent: 20px';
    		} elseif ($menuitem == '0') {
      		$linktomenu = '<span style="color:red">La página está en el menu</span>';
      		$csstyle    = 'text-indent: 0px';
    		} //$menuitem == '0'

    		$addpage = '';
    		$delete = '<a href="../functions/pages.php?function=delete&id=' . $id . '&parent=' . $parent . '" onclick="return confirmDelete(this);">Borrar</a>';
    		
    		$row_color = ($row_count % 2) ? $color1 : $color2;
    
    		if ($hassub == '1') {
      		$removesub = '<a style="color:green" href="../functions/pages.php?function=remove-sub&id=' . $id . '">Remove Sub-Menu</a>';
    		} else {
      		$removesub = '<span style="color:red">no sub-menu</span>';
    		}

    		if ($list['hidden'] == 0) {
      		$hidden = '<span id="hidden_page' . $id . '"><a  href="javascript:hidePage(' . $id . ',1);" >Ocultar</a></span>';
    		} else {
      		$hidden = '<span id="hidden_page' . $id . '"><a  href="javascript:hidePage(' . $id . ',0);"  >Mostrar</a></span>';
    		}

    		$names3 .= '
    		<tr>
      		<td bgcolor="' . $row_color . '" nowrap>
        			<a style="' . $csstyle . '" href="' . $editlink . '">&bull; ' . $linktitle . ' ' . $addpage . '</a><br>
      		</td>
      
      		<td>
        			<a href="' . $editlink . '">
        				Editar
        			</a> 
        			| ' . $delete . ' | 
        			<a target="_blank" href="../index.php?act=pages&id=' . $id . '">
        				Vista previa
        			</a> 
        			| 
        			<a href="index.php?edit=pages&function=add&subid=' . $id . '&subpagename=' . $pagename . '">
        				Agregar sub-páginas
        			</a> 
        			| 
        			' . $hidden . '
      		</td>
     			
     			<td>
     				<form action="../functions/pages.php?function=order" method="post">
        				<input name="pos" type="text" size="1" value="' . $pos . '"> 
        				<input name="posid" type="hidden" value="' . $id . '">
        				
        				<br />
        				
        				<input type="submit" value="Guardar" style="padding:10px;" />
        			</form>
      		</td>
    		</tr>
    		
    		<tr>
    			<td colspan="3" style="border-bottom: 1px dashed #CCCCCC; ">
      			<a onclick="showSubs(\'subs' . $yy++ . '\')" href="javascript:void(0)" style="font-size:10px;background-color:#F2F2F2;border:1px dashed #CCCCCC;padding:2px">
      				Sub Pages
      			</a> 
      			
      			<div id="subs' . $zz++ . '" class="subs' . $xx++ . '" style="display:none; height:400px; background-color:#CCCCCC; border:1px dashed #CCCCCC">
        				<iframe src="subs.php?id=' . $id . '&pagename=' . $pagename . '" frameborder="0" scrolling="auto" width="100%" height="400"></iframe>
					</div>
    			</td>
			</tr>';
    		
    		$row_count++;
  		} 
  		
  		return '
  		<table width="100%"  border="0" cellspacing="0" cellpadding="0" class="style2">
			<tr bgcolor="#f4f7f4">
				<td width="33%">
          		<strong>Nombre de la Página </strong>
          	</td>
					
				<td>
					<strong>Funciones</strong>
				</td>
	  				
	  			<td width="15%">
	  				<strong>Posicionamiento en el menu</strong>
	  			</td>
			</tr>
			' . $names3 . '
		</table>';
	}
function fixTime($time)
{
//  error_log("time: $time");
  $pi      = explode(" ", $time);
  $pi_time = explode(":", $pi[0]);
  if (($pi[1] == 'pm' or $pi[1] == 'PM') && ($pi_time[0] == '12')) {
    $time = str_replace(":", "", $pi[0]);
    return $time;
  } //($pi[1] == 'pm' or $pi[1] == 'PM') && ($pi_time[0] == '12')
  elseif (($pi[1] == 'pm' or $pi[1] == 'PM') or (($pi[1] == 'am' or $pi[1] == 'AM') && ($pi_time[0] == '12'))) {
    $time1 = str_replace(":", "", $pi[0]);
    $time  = $time1 + 1200;
    return $time;
  } //($pi[1] == 'pm' or $pi[1] == 'PM') or (($pi[1] == 'am' or $pi[1] == 'AM') && ($pi_time[0] == '12'))
  else {
    $time = str_replace(":", "", $pi[0]);
    return $time;
  }
}

	function getConfig(){
		global $database;
  		
  		$test = $database->select("SELECT * FROM config where id = '" . RID . "'  ");
  		
  		if ($test == FALSE) {
  			$query = $database->query("SELECT * FROM config where id = 1  ");
  		} else {
  			$query = $database->query("SELECT * FROM config where id = '" . RID . "'  ");
  		}
  		
  		$results = mysql_fetch_array($query);
  		
  		foreach ($results as $val) {
  			$val = $val;
  		} 

  		return $results;
	}

	function openTime($array, $type){
		$times = explode("+", $array);
		
		if ($type == 'open') {
			$open  = unserialize($times[0]);
			return $open;
		} elseif ($type == 'close') {
			$close = unserialize($times[1]);
			return $close;
  		} elseif ($type == 'blackout_start') {
  			$b1    = unserialize($times[2]);
  			return $b1;
  		} elseif ($type == 'blackout_end') {
  			$b2    = unserialize($times[3]);
    		return $b2;
  		} 
	}
	
	function isOpen($restaurant){
		$open = openTime($restaurant['hours'],'open');
		$closed= openTime($restaurant['hours'],'close');
		
		$blackout_start = openTime($restaurant['hours'],'blackout_start');
		$blackout_end = openTime($restaurant['hours'],'blackout_end');
	
		$date = date("F j, Y, g:i a");	
		$time = date("g:i a");

		$dayofweek = date("l");
		$daysOfWeek = array("Sunday" => 0, "Monday" => 1, "Tuesday" => 2, "Wednesday" => 3, "Thursday" => 4, "Friday" => 5, "Saturday" => 6);
		$dayOfWeekNum = $daysOfWeek[$dayofweek];

		$open_time = $open[$dayOfWeekNum];	
		$close_time = $closed[$dayOfWeekNum];
		
		$blackout_start_time = $blackout_start[$dayOfWeekNum];
		$blackout_end_time =   $blackout_end[$dayOfWeekNum];
	
		if (!$open_time){
			$open_time = "12:00 am";
		}
	
		if (!$close_time){
			$close_time = "12:00 am";
		}

		$open_time_c = fixTime($open_time);
		$close_time_c = fixTime($close_time);
		$thisTime = fixTime($time);

		if($close_time_c < "1200"){
			$close_time_c = $close_time_c + 2400;
		}


		if ( ($thisTime < $open_time_c or $thisTime > $close_time_c or $restaurant['enabled'] == 1)
				or ( $thisTime > fixTime($blackout_start_time) && $thisTime < fixTime($blackout_end_time) )
				or ($open_time_c == "") ) {
			return false;
		} else {
			return true;
  		}
	}
	
	function isDestacado($restaurant){
		if($restaurant['pizza_builder'] == 1){
			return true;
		} else {
			return false;
		}
	}

	function verify_phone($num, $min, $max){
		// first line will remove all spaces
  		$trimmed = str_replace(' ', '', trim($num));
  		
  		// regex expression
  		$regex   = "/^[()\/0-9-]{" . $min . "," . $max . "}$/i";
  		
  		if (preg_match($regex, $trimmed))
  			return true;
  		
  		return false;
	}
	
	function is_valid_expiration($month, $year){
		//if the month or year are not numeric...skipit
  		if ((!is_numeric($month)) || (!is_numeric($year))) {
    		return false;
  		} //(!is_numeric($month)) || (!is_numeric($year))
  		//set the current year to the year format sent in
  		//and convert to integer
  		//if length is 2 (03) or 4 (2003) else...skipit
  		
  		if (strlen($year) == 4) {
    		$current_year = (integer) date('Y');
  		} elseif (strlen($year) == 2) {
    		$current_year = (integer) date('y');
  		} else {
    		return false;
  		}
  		
  		//convert the curent month to integer
  		$current_month = (integer) date('m');
  		
  		//valid values for month are 1 thru 12
  		if (($month < 1) || ($month > 12)) {
  			return false;
  		} //($month < 1) || ($month > 12)
  		//if the year passed in is before the current year of
  		//more than 10 years out...skipit
  		
  		if (($year < $current_year) || ($year > ($current_year + 10))) {
    		return false;
  		} //($year < $current_year) || ($year > ($current_year + 10))
  		//if the year passed in is the same as the current year
  		//and the month is before the current month...skipit
  		
  		if (($year == $current_year) && ($month < $current_month)) {
    		return false;
  		} //($year == $current_year) && ($month < $current_month)
  			//passed all tests, expiration date is ok
  	
  		return true;
	}

	function check_email_address($email){
  		return filter_var($email, FILTER_VALIDATE_EMAIL);
	}

	function validateCCdate($month, $year){
  		$thismonth = date("m");
  		$thisyear  = date("y");
  		
  		if ($month < $thismonth && $year <= $thisyear) {
    		echo 0;
    		exit;
    		return false;
  		} else {
    		echo $month;
    		echo $year;
    		exit;
    		return true;
  		}
	}

function validateCC($cc_num, $type)
{
  if ($type == "American") {
    $denum = "American Express";
  } //$type == "American"
  elseif ($type == "Dinners") {
    $denum = "Diner's Club";
  } //$type == "Dinners"
    elseif ($type == "Discover") {
    $denum = "Discover";
  } //$type == "Discover"
    elseif ($type == "Master") {
    $denum = "Master Card";
  } //$type == "Master"
    elseif ($type == "Visa") {
    $denum = "Visa";
  } //$type == "Visa"
  if ($type == "American") {
    $pattern = "/^([34|37]{2})([0-9]{13})$/"; //American Express
    if (preg_match($pattern, $cc_num)) {
      $verified = true;
    } //preg_match($pattern, $cc_num)
    else {
      $verified = false;
    }
  } //$type == "American"
  elseif ($type == "Dinners") {
    $pattern = "/^([30|36|38]{2})([0-9]{12})$/"; //Diner's Club
    if (preg_match($pattern, $cc_num)) {
      $verified = true;
    } //preg_match($pattern, $cc_num)
    else {
      $verified = false;
    }
  } //$type == "Dinners"
    elseif ($type == "Discover") {
    $pattern = "/^([6011]{4})([0-9]{12})$/"; //Discover Card
    if (preg_match($pattern, $cc_num)) {
      $verified = true;
    } //preg_match($pattern, $cc_num)
    else {
      $verified = false;
    }
  } //$type == "Discover"
    elseif ($type == "Master") {
    $pattern = "/^([51|52|53|54|55]{2})([0-9]{14})$/"; //Mastercard
    if (preg_match($pattern, $cc_num)) {
      $verified = true;
    } //preg_match($pattern, $cc_num)
    else {
      $verified = false;
    }
  } //$type == "Master"
    elseif ($type == "Visa") {
    $pattern = "/^([4]{1})([0-9]{12,15})$/"; //Visa
    if (preg_match($pattern, $cc_num)) {
      $verified = true;
    } //preg_match($pattern, $cc_num)
    else {
      $verified = false;
    }
  } //$type == "Visa"
  if ($verified == false) {
    //Do something here in case the validation fails
    return false;
  } //$verified == false
  else { //if it will pass...do something
    return true;
  }
}
/*
###############################################
####                                       ####
####    Author : Harish Chauhan            ####
####    Date   : 27 Sep,2004               ####
####    Updated:                           ####
####                                       ####
###############################################

*/
function dollar($amount)
{
  $new_amount = "\$" . sprintf("%.2f", $amount);
  return $new_amount;
}

	function treatGet($text){
  		/* Previously used prior to 3.0.13 
  		"Good but your not right..." - Roy Castle (Catch Phrase)
  
  		$text = preg_replace("/(\<script)(.*?)(script>)/si", "", $text);
  		$text = strip_tags($text);
  		$text = str_replace(array("'","\"",">","<","\\"), "", $text);
  
  		*/
  		
  		/* Strong but too restrictive  
  		$text = htmlspecialchars($text, ENT_QUOTES); 
  		*/
  		
  		// safen most dangerous chars 
  		$text = str_replace(array( '&', '"', '<', '>'), array('&amp;', '&quot;', '&lt;', '&gt;'), $text);
  		return $text;
	}
	
function format_phone($ph)
{
  $npa      = substr($ph, 0, 3) . '';
  $areaCode = '(' . $npa . ') ';
  $npa2     = substr($ph, 3, 3) . '-';
  $num      = substr($ph, 6, 4);
  return $areaCode . $npa2 . $num;
}
class Page
{
  var $total_records = 1; ///Total Records returned by sql query
  var $records_per_page = 1; ///how many records would be displayed at a time
  var $page_name = ""; ///page name on which the class is called
  var $start = 0;
  var $page = 0;
  var $total_page = 0;
  var $current_page;
  var $remain_page;
  var $show_prev_next = true;
  var $show_scroll_prev_next = false;
  var $show_first_last = false;
  var $show_disabled_links = true;
  var $scroll_page = 0;
  var $qry_str = "";
  var $link_para = "";
  var $jsHandler = "";
  /* returns boolean value if it is last page or not*/
  function is_last_page()
  {
    return $this->page >= $this->total_page - 1 ? true : false;
  }
  /* param : Void
  returns boolean value if it is first page or not*/
  function is_first_page()
  {
    return $this->page == 0 ? true : false;
  }
  /**
   * Input : Void
   * Return: The current page 
   */
  function current_page()
  {
    return $this->page + 1;
  }
  /**
   * Return the total pages.
   */
  function total_page()
  {
    return $this->total_page == 0 ? 1 : $this->total_page;
  }
  //@param : $show = if you want to show desabled links on navigation links.
  //
  function show_disabled_links($show = TRUE)
  {
    $this->show_disabled_links = $show;
  }
  //@param : $link_para = if you want to pass any parameter to link
  //
  function set_link_parameter($link_para)
  {
    $this->link_para = $link_para;
  }
  function set_page_name($page_name)
  {
    $this->page_name = $page_name;
  }
  /**
   * Function is used to set the javascript handler function
   * @param $jsHandler: String Javascript function name
   * @return  void; 
   * @uses Function will use javascript handler function for pagging. It will pass the two parameters to 
   * javascript function. First is page name and the second one is query string.
   */
  function setJSHandler($jsHandler)
  {
    $this->jsHandler = $jsHandler;
  }
  //@param : str= query string you want to pass to links.
  function set_qry_string($str = "", $usePost = true)
  {

    $this->qry_str = "&" . preg_replace("/&?page=\d*/", "", $str);
    
    if ($usePost) {
      foreach ($_POST as $key => $value)
        if (strpos($this->qry_str, "$key=") === false)
          $this->qry_str .= "&$key=$value";
      foreach ($_GET as $key => $value)
        if (strpos($this->qry_str, "$key=") === false)
          $this->qry_str .= "&$key=$value";
    } //$usePost
    $this->qry_str = "&" . preg_replace("/&?page=\d*/", "", $this->qry_str);
  }
  function set_scroll_page($scroll_num = 0)
  {
    if ($scroll_num != 0)
      $this->scroll_page = $scroll_num;
    else
      $this->scroll_page = $this->total_records;
  }
  function set_total_records($total_records)
  {
    if ($total_records < 0)
      $total_records = 0;
    $this->total_records = $total_records;
  }
  function set_records_per_page($records_per_page)
  {
    if ($records_per_page <= 0)
      $records_per_page = $this->total_records;
    $this->records_per_page = $records_per_page;
  }
  /* @params
   * 	$page_name = Page name on which class is integrated. i.e. $_SERVER['PHP_SELF']
   *  	$total_records=Total records returnd by sql query.
   * 	$records_per_page=How many projects would be displayed at a time 
   *		$scroll_num= How many pages scrolled if we click on scroll page link. 
   * 				i.e if we want to scroll 6 pages at a time then pass argument 6.
   * 	$show_prev_next= boolean(true/false) to show prev Next Link
   * 	$show_scroll_prev_next= boolean(true/false) to show scrolled prev Next Link
   * 	$show_first_last= boolean(true/false) to show first last Link to move first and last page.
   */
  function set_page_data($page_name, $total_records, $records_per_page = 1, $scroll_num = 0, $show_prev_next = true, $show_scroll_prev_next = false, $show_first_last = false)
  {
    $this->set_total_records($total_records);
    $this->set_records_per_page($records_per_page);
    $this->set_scroll_page($scroll_num);
    $this->set_page_name($page_name);
    $this->show_prev_next        = $show_prev_next;
    $this->show_scroll_prev_next = $show_scroll_prev_next;
    $this->show_first_last       = $show_first_last;
  }
  /* @params
   *  $user_link= if you want to display your link i.e if you want to user '>>' instead of [first] link then use
   Page::get_first_page_nav(">>") OR for image
   Page::get_first_page_nav("<img src='' alt='first'>") 
   $link_para: link parameters i.e if you want ot use another parameters such as class.
   Page::get_first_page_nav(">>","class=myStyleSheetClass")
   */
  function get_first_page_nav($user_link = "", $link_para = "", $returnHtml = false)
  {
    if ($this->total_page <= 1)
      return;
    if (trim($user_link) == "")
      $user_link = "First";
    if (empty($link_para))
      $link_para = $this->link_para;
    $html = "";
    if (!$this->is_first_page() && $this->show_first_last) {
      if (empty($this->jsHandler))
        $html = ' <a href="' . $this->page_name . '?page=0' . $this->qry_str . '" ' . $link_para . '>' . $user_link . '</a> ';
      else
        $html = ' <a href="javascript:void(0);" onclick="' . $this->jsHandler . '(\'' . $this->page_name . '\',\'page=0' . $this->qry_str . '\')" ' . $link_para . '>' . $user_link . '</a> ';
    } //!$this->is_first_page() && $this->show_first_last
    elseif ($this->show_first_last && $this->show_disabled_links)
      $html = $user_link;
    if ($returnHtml)
      return $html;
    echo $html;
  }
  function get_last_page_nav($user_link = "", $link_para = "", $returnHtml = false)
  {
    if ($this->total_page <= 1)
      return;
    if (trim($user_link) == "")
      $user_link = "Last";
    if (empty($link_para))
      $link_para = $this->link_para;
    $html = "";
    if (!$this->is_last_page() && $this->show_first_last) {
      if (empty($this->jsHandler))
        $html = ' <a href="' . $this->page_name . '?page=' . ($this->total_page - 1) . $this->qry_str . '" ' . $link_para . '>' . $user_link . '</a> ';
      else
        $html = ' <a href="javascript:void(0);" onclick="' . $this->jsHandler . '(\'' . $this->page_name . '\',\'page=' . ($this->total_page - 1) . $this->qry_str . '\')" ' . $link_para . '>' . $user_link . '</a> ';
    } //!$this->is_last_page() && $this->show_first_last
    elseif ($this->show_first_last && $this->show_disabled_links)
      $html = $user_link;
    if ($returnHtml)
      return $html;
    echo $html;
  }
  function get_next_page_nav($user_link = "", $link_para = "", $returnHtml = false)
  {
    if ($this->total_page <= 1)
      return;
    if (trim($user_link) == "")
      $user_link = " Next &raquo;";
    if (empty($link_para))
      $link_para = $this->link_para;
    $html = "";
    if (!$this->is_last_page() && $this->show_prev_next) {
      if (empty($this->jsHandler))
        $html = ' <a href="' . $this->page_name . '?page=' . ($this->page + 1) . $this->qry_str . '" ' . $link_para . '>' . $user_link . '</a> ';
      else
        $html = ' <a href="javascript:void(0);" onclick="' . $this->jsHandler . '(\'' . $this->page_name . '\',\'page=' . ($this->page + 1) . $this->qry_str . '\')" ' . $link_para . '>' . $user_link . '</a> ';
    } //!$this->is_last_page() && $this->show_prev_next
    elseif ($this->show_prev_next && $this->show_disabled_links)
      $html = $user_link;
    if ($returnHtml)
      return $html;
    echo $html;
  }
  function get_prev_page_nav($user_link = "", $link_para = "", $returnHtml = false)
  {
    if ($this->total_page <= 1)
      return;
    if (trim($user_link) == "")
      $user_link = "&laquo; Prev ";
    if (empty($link_para))
      $link_para = $this->link_para;
    $html = "";
    if (!$this->is_first_page() && $this->show_prev_next) {
      if (empty($this->jsHandler))
        $html = ' <a href="' . $this->page_name . '?page=' . ($this->page - 1) . $this->qry_str . '" ' . $link_para . '>' . $user_link . '</a> ';
      else
        $html = ' <a href="javascript:void(0);" onclick="' . $this->jsHandler . '(\'' . $this->page_name . '\',\'page=' . ($this->page - 1) . $this->qry_str . '\')" ' . $link_para . '>' . $user_link . '</a> ';
    } //!$this->is_first_page() && $this->show_prev_next
    elseif ($this->show_prev_next && $this->show_disabled_links)
      $html = $user_link;
    if ($returnHtml)
      return $html;
    echo $html;
  }
  function get_scroll_prev_page_nav($user_link = "", $link_para = "", $returnHtml = false)
  {
    if ($this->scroll_page >= $this->total_page)
      return;
    if (trim($user_link) == "")
      $user_link = "Prev[$this->scroll_page]";
    $html = "";
    if ($this->page > $this->scroll_page && $this->show_scroll_prev_next) {
      if (empty($this->jsHandler))
        $html = ' <a href="' . $this->page_name . '?page=' . ($this->page - $this->scroll_page) . $this->qry_str . '" ' . $link_para . '>' . $user_link . '</a> ';
      else
        $html = ' <a href="javascript:void(0);" onclick="' . $this->jsHandler . '(\'' . $this->page_name . '\',\'page=' . ($this->page - $this->scroll_page) . $this->qry_str . '\')" ' . $link_para . '>' . $user_link . '</a> ';
    } //$this->page > $this->scroll_page && $this->show_scroll_prev_next
    elseif ($this->show_scroll_prev_next && $this->show_disabled_links)
      $html = $user_link;
    if ($returnHtml)
      return $html;
    echo $html;
  }
  function get_scroll_next_page_nav($user_link = "", $link_para = "", $returnHtml = false)
  {
    if ($this->scroll_page >= $this->total_page)
      return;
    if (trim($user_link) == "")
      $user_link = "Next[$this->scroll_page]";
    if (empty($link_para))
      $link_para = $this->link_para;
    $html = "";
    if ($this->total_page > $this->page + $this->scroll_page && $this->show_scroll_prev_next) {
      if (empty($this->jsHandler))
        $html = ' <a href="' . $this->page_name . '?page=' . ($this->page + $this->scroll_page) . $this->qry_str . '" ' . $link_para . '>' . $user_link . '</a> ';
      else
        $html = ' <a href="javascript:void(0);" onclick="' . $this->jsHandler . '(\'' . $this->page_name . '\',\'page=' . ($this->page + $this->scroll_page) . $this->qry_str . '\')" ' . $link_para . '>' . $user_link . '</a> ';
    } //$this->total_page > $this->page + $this->scroll_page && $this->show_scroll_prev_next
    elseif ($this->show_scroll_prev_next && $this->show_disabled_links)
      $html = $user_link;
    if ($returnHtml)
      return $html;
    echo $html;
  }
  function get_number_page_nav($link_para = "", $returnHtml = false)
  {
    if (empty($link_para))
      $link_para = $this->link_para;
    $j           = 0;
    $scroll_page = $this->scroll_page;
    if ($this->page > ($scroll_page / 2))
      $j = $this->page - intval($scroll_page / 2);
    if ($j + $scroll_page > $this->total_page)
      $j = $this->total_page - $scroll_page;
    if ($j < 0)
      $i = 0;
    else
      $i = $j;
    $html = "";
    for (; $i < $j + $scroll_page && $i < $this->total_records; $i++) {
      if ($i == $this->page)
        $html .= ($i + 1);
      else {
        if (empty($this->jsHandler))
          $html .= ' <a href="' . $this->page_name . '?page=' . $i . $this->qry_str . '" ' . $link_para . '>' . ($i + 1) . '</a> ';
        else
          $html .= ' <a href="javascript:void(0);" onclick="' . $this->jsHandler . '(\'' . $this->page_name . '\',\'page=' . $i . $this->qry_str . '\')" ' . $link_para . '>' . ($i + 1) . '</a> ';
      }
    } //; $i < $j + $scroll_page && $i < $this->total_records; $i++
    if ($returnHtml)
      return $html;
    echo $html;
  }
  function get_page_nav($link_para = "", $returnHtml = true)
  {
    if ($this->total_records <= 0)
      return false;
    if ($this->total_records <= $this->records_per_page)
      return "";
    if (!empty($link_para))
      $this->link_para = $link_para;
    $html = "";
    $this->calculate();
    $html .= $this->get_first_page_nav("", $this->link_para, $returnHtml);
    $html .= $this->get_scroll_prev_page_nav("", $this->link_para, $returnHtml);
    $html .= $this->get_prev_page_nav("", $this->link_para, $returnHtml);
    $html .= $this->get_number_page_nav($this->link_para, $returnHtml);
    $html .= $this->get_next_page_nav("", $this->link_para, $returnHtml);
    $html .= $this->get_scroll_next_page_nav("", $this->link_para, $returnHtml);
    $html .= $this->get_last_page_nav("", $this->link_para, $returnHtml);
    if ($returnHtml)
      return $html;
    return;
  }
  function calculate()
  {
    $this->page = $_REQUEST['page'];
    if (!is_numeric($this->page))
      $this->page = 0;
    $this->start      = $this->page * $this->records_per_page;
    $this->total_page = @intval($this->total_records / $this->records_per_page);
    if ($this->total_records % $this->records_per_page != 0)
      $this->total_page++;
  }
  function get_limit_query($qry = "")
  {
    $this->calculate();
    return $qry . " LIMIT $this->start,$this->records_per_page";
  }
}
/* Example 1
$page=new Page();
$page->set_total_records($total_records); //number of Total records
$page->set_records_per_page(1); //number of records displays on a single page
//$page->show_prev_next=false; //Shows Previous and Next Page links
$page->show_scroll_prev_next=true; //Shows Previous and Next Page links
$page->show_first_last=true; //Shows first and Last Page links
$page->set_page_name('dsays2.php'); //set the page name on which paging has to be doen

echo $qry=$page->get_limit_query($qry); //return the query with limits
echo "<br>";
$db->query($qry);
while($row=$db->fetchObject())
{
echo $row->username."<br>";
}
$page->get_page_nav(); // Shows the nevigation bars;
*/
/* Example 2
$page=new Page();


$page->set_page_data('dsays2.php',$total_records,7,0,false,false,true);

*/
class AdRotator
{
  var $iMax = "";
  var $imageIndex = "";
  var $imageNames = "";
  var $linkNames = "";
  function AdRotator($images, $links = NULL)
  {
    if (!is_array($images))
      die("error: cant find image array");
    else {
      $this->iMax       = count($images);
      $this->imageNames = $images;
      $this->linkNames  = $links;
    }
  }
  function rotate($num)
  {
    if ($num > $this->iMax)
      die("error: not enough images to randomize");
    $image_index = array();
    while (count($image_index) < $num) {
      $pin = rand(0, $this->iMax - 1);
      if (!in_array("$pin", $image_index))
        array_push($image_index, $pin);
    } //count($image_index) < $num
    $this->imageIndex = $image_index;
  }
  function getImages()
  {
    $tmp = array();
    for ($idx = 0; $idx < count($this->imageIndex); $idx++)
      array_push($tmp, $this->imageNames[$this->imageIndex[$idx]]);
    return $tmp;
  }
  function showAds($orientation = NULL /* say VERTICAL if you need vertical orientation */ , $link_style = NULL, $image_style = NULL /* this is the css class that can be used */ )
  {
    if (!$link_style) {
      $link_style = "text-decoration:none;";
    } //!$link_style
    if (!$image_style) {
      $image_style = "background:#f0f0f0;";
    } //!$image_style
    $html = '';
    for ($idx = 0; $idx < count($this->imageIndex); $idx++) {
      $html .= "<a style='" . $link_style . "' href='" . $this->linkNames[$this->imageIndex[$idx]] . "'><img border=0 src='" . $this->imageNames[$this->imageIndex[$idx]] . "' style='" . $image_style . "'></a>\n";
      if ($orientation == "VERTICAL")
        $html .= "<br>\n";
    } //$idx = 0; $idx < count($this->imageIndex); $idx++
    return $html;
  }
}
class ThumbHandle
{
  var $width;
  var $height;
  function ThumbHandle($width, $height)
  {
    $this->width  = $width;
    $this->height = $height;
  }
  function generateJPEG($imageName, $originalPath, $destinationPath)
  {
    $len  = strlen($imageName);
    $pos  = strpos($imageName, ".");
    $type = strtolower(substr($imageName, $pos + 1, $len));
    if ($type != "jpeg" && $type != "jpg") {
      return;
    } //$type != "jpeg" && $type != "jpg"
    $destimg = imagecreatetruecolor($this->width, $this->height) or die("Problem In Creating image");
    $srcimg = imagecreatefromjpeg($originalPath . $imageName) or die("Problem In opening Source Image");
    imagecopyresampled($destimg, $srcimg, 0, 0, 0, 0, $this->width, $this->height, imagesx($srcimg), imagesy($srcimg)) or die("Problem In resizing");
    if (!is_dir($destinationPath)) {
      @mkdir($destinationPath);
    } //!is_dir($destinationPath)
    @chmod($destinationPath, 0777);
    imagejpeg($destimg, $destinationPath . $imageName) or die("Problem In saving");
    @chmod($destinationPath, 0755);
  }
}
function prepareKeywords($text)
{
  $text = strip_tags($text);
  $text = str_replace("&ldquo", " ", $text);
  $text = str_replace("&rdquo", " ", $text);
  $text = str_replace("&rsquo", " ", $text);
  $text = str_replace("&lsquo", " ", $text);
  $text = str_replace("&rdquo", " ", $text);
  $text = str_replace("&quot", " ", $text);
  $text = str_replace("&nbsp;", " ", $text);
  $text = str_replace("&bull", "", $text);
  $text = str_replace("&#39;", "'", $text);
  return $text;
}
function prepareDescription($text)
{
  $text = strip_tags($text);
  $text = substr($text, 0, 200);
  $text = str_replace("&ldquo", " ", $text);
  $text = str_replace("&rdquo", " ", $text);
  $text = str_replace("&rsquo", " ", $text);
  $text = str_replace("&lsquo", " ", $text);
  $text = str_replace("&rdquo", " ", $text);
  $text = str_replace("&quot", " ", $text);
  $text = str_replace("&nbsp;", " ", $text);
  $text = str_replace("&bull", "", $text);
  $text = str_replace("&#39;", "'", $text);
  return $text;
}
function prepareTitle($text)
{
  $text = explode(',', $text);
  $text = array_slice($text, 0, 4);
  $text = implode("  ", $text);
  $text = strip_tags($text);
  $text = str_replace("&ldquo", " ", $text);
  $text = str_replace("&rdquo", " ", $text);
  $text = str_replace("&rsquo", " ", $text);
  $text = str_replace("&lsquo", " ", $text);
  $text = str_replace("&rdquo", " ", $text);
  $text = str_replace("&quot", " ", $text);
  $text = str_replace("-", " ", $text);
  $text = str_replace("_", " ", $text);
  return $text;
}
function prepareURL($text)
{
  $text = strip_tags($text);
  $text = $text;
  $text = str_replace("&ldquo", " ", $text);
  $text = str_replace("&rdquo", " ", $text);
  $text = str_replace("&rsquo", " ", $text);
  $text = str_replace("&lsquo", " ", $text);
  $text = str_replace("&rdquo", " ", $text);
  $text = str_replace("&quot", " ", $text);
  $text = str_replace("&nbsp;", " ", $text);
  $text = str_replace("&bull", "", $text);
  $text = str_replace("&#39;", "'", $text);
  $text = str_replace("?", "", $text);
  $text = str_replace(" ", "-", $text);
  $text = str_replace("/", "-", $text);
  return $text;
}
class autokeyword
{
  //declare variables
  //the site contents
  var $contents;
  var $encoding;
  //the generated keywords
  var $keywords;
  //minimum word length for inclusion into the single word
  //metakeys
  var $wordLengthMin;
  var $wordOccuredMin;
  //minimum word length for inclusion into the 2 word
  //phrase metakeys
  var $word2WordPhraseLengthMin;
  var $phrase2WordLengthMinOccur;
  //minimum word length for inclusion into the 3 word
  //phrase metakeys
  var $word3WordPhraseLengthMin;
  //minimum phrase length for inclusion into the 2 word
  //phrase metakeys
  var $phrase2WordLengthMin;
  var $phrase3WordLengthMinOccur;
  //minimum phrase length for inclusion into the 3 word
  //phrase metakeys
  var $phrase3WordLengthMin;
  function autokeyword($params, $encoding)
  {
    //get parameters
    $this->encoding = $encoding;
    mb_internal_encoding($encoding);
    $this->contents                  = $this->replace_chars($params['content']);
    // single word
    $this->wordLengthMin             = $params['min_word_length'];
    $this->wordOccuredMin            = $params['min_word_occur'];
    // 2 word phrase
    $this->word2WordPhraseLengthMin  = $params['min_2words_length'];
    $this->phrase2WordLengthMin      = $params['min_2words_phrase_length'];
    $this->phrase2WordLengthMinOccur = $params['min_2words_phrase_occur'];
    // 3 word phrase
    $this->word3WordPhraseLengthMin  = $params['min_3words_length'];
    $this->phrase3WordLengthMin      = $params['min_3words_phrase_length'];
    $this->phrase3WordLengthMinOccur = $params['min_3words_phrase_occur'];
    //parse single, two words and three words
  }
  function get_keywords()
  {
    $keywords = $this->parse_words() . $this->parse_2words() . $this->parse_3words();
    return substr($keywords, 0, -2);
  }
  //turn the site contents into an array
  //then replace common html tags.
  function replace_chars($content)
  {
    //convert all characters to lower case
    $content      = mb_strtolower($content);
    //$content = mb_strtolower($content, "UTF-8");
    $content      = strip_tags($content);
    $punctuations = array(
      ',',
      ')',
      '(',
      '.',
      "'",
      '"',
      '<',
      '>',
      ';',
      '!',
      '?',
      '/',
      '-',
      '_',
      '[',
      ']',
      ':',
      '+',
      '=',
      '#',
      '$',
      '&quot;',
      '&copy;',
      '&gt;',
      '&lt;',
      chr(10),
      chr(13),
      chr(9)
    );
    $content      = str_replace($punctuations, " ", $content);
    // replace multiple gaps
    $content      = preg_replace('/ {2,}/si', " ", $content);
    return $content;
  }
  //single words META KEYWORDS
  function parse_words()
  {
    //list of commonly used words
    // this can be edited to suit your needs
    $common = array(
      "able",
      "about",
      "above",
      "act",
      "add",
      "afraid",
      "after",
      "again",
      "against",
      "age",
      "ago",
      "agree",
      "all",
      "almost",
      "alone",
      "along",
      "already",
      "also",
      "although",
      "always",
      "am",
      "amount",
      "an",
      "and",
      "anger",
      "angry",
      "animal",
      "another",
      "answer",
      "any",
      "appear",
      "apple",
      "are",
      "arrive",
      "arm",
      "arms",
      "around",
      "arrive",
      "as",
      "ask",
      "at",
      "attempt",
      "aunt",
      "away",
      "back",
      "bad",
      "bag",
      "bay",
      "be",
      "became",
      "because",
      "become",
      "been",
      "before",
      "began",
      "begin",
      "behind",
      "being",
      "bell",
      "belong",
      "below",
      "beside",
      "best",
      "better",
      "between",
      "beyond",
      "big",
      "body",
      "bone",
      "born",
      "borrow",
      "both",
      "bottom",
      "box",
      "boy",
      "break",
      "bring",
      "brought",
      "bug",
      "built",
      "busy",
      "but",
      "buy",
      "by",
      "call",
      "came",
      "can",
      "cause",
      "choose",
      "close",
      "close",
      "consider",
      "come",
      "consider",
      "considerable",
      "contain",
      "continue",
      "could",
      "cry",
      "cut",
      "dare",
      "dark",
      "deal",
      "dear",
      "decide",
      "deep",
      "did",
      "die",
      "do",
      "does",
      "dog",
      "done",
      "doubt",
      "down",
      "during",
      "each",
      "ear",
      "early",
      "eat",
      "effort",
      "either",
      "else",
      "end",
      "enjoy",
      "enough",
      "enter",
      "even",
      "ever",
      "every",
      "except",
      "expect",
      "explain",
      "fail",
      "fall",
      "far",
      "fat",
      "favor",
      "fear",
      "feel",
      "feet",
      "fell",
      "felt",
      "few",
      "fill",
      "find",
      "fit",
      "fly",
      "follow",
      "for",
      "forever",
      "forget",
      "from",
      "front",
      "gave",
      "get",
      "gives",
      "goes",
      "gone",
      "good",
      "got",
      "gray",
      "great",
      "green",
      "grew",
      "grow",
      "guess",
      "had",
      "half",
      "hang",
      "happen",
      "has",
      "hat",
      "have",
      "he",
      "hear",
      "heard",
      "held",
      "hello",
      "help",
      "her",
      "here",
      "hers",
      "high",
      "hill",
      "him",
      "his",
      "hit",
      "hold",
      "hot",
      "how",
      "however",
      "I",
      "if",
      "ill",
      "in",
      "indeed",
      "instead",
      "into",
      "iron",
      "is",
      "it",
      "its",
      "just",
      "keep",
      "kept",
      "knew",
      "know",
      "known",
      "late",
      "least",
      "led",
      "left",
      "lend",
      "less",
      "let",
      "like",
      "likely",
      "likr",
      "lone",
      "long",
      "look",
      "lot",
      "make",
      "many",
      "may",
      "me",
      "mean",
      "met",
      "might",
      "mile",
      "mine",
      "moon",
      "more",
      "most",
      "move",
      "much",
      "must",
      "my",
      "near",
      "nearly",
      "necessary",
      "neither",
      "never",
      "next",
      "no",
      "none",
      "nor",
      "not",
      "note",
      "nothing",
      "now",
      "number",
      "of",
      "off",
      "often",
      "oh",
      "on",
      "once",
      "only",
      "or",
      "other",
      "ought",
      "our",
      "out",
      "please",
      "prepare",
      "probable",
      "pull",
      "pure",
      "push",
      "put",
      "raise",
      "ran",
      "rather",
      "reach",
      "realize",
      "reply",
      "require",
      "rest",
      "run",
      "said",
      "same",
      "sat",
      "saw",
      "say",
      "see",
      "seem",
      "seen",
      "self",
      "sell",
      "sent",
      "separate",
      "set",
      "shall",
      "she",
      "should",
      "side",
      "sign",
      "since",
      "so",
      "sold",
      "some",
      "soon",
      "sorry",
      "stay",
      "step",
      "stick",
      "still",
      "stood",
      "such",
      "sudden",
      "suppose",
      "take",
      "taken",
      "talk",
      "tall",
      "tell",
      "ten",
      "than",
      "thank",
      "that",
      "the",
      "their",
      "them",
      "then",
      "there",
      "therefore",
      "these",
      "they",
      "this",
      "those",
      "though",
      "through",
      "till",
      "to",
      "today",
      "told",
      "tomorrow",
      "too",
      "took",
      "tore",
      "tought",
      "toward",
      "tried",
      "tries",
      "trust",
      "try",
      "turn",
      "two",
      "under",
      "until",
      "up",
      "upon",
      "us",
      "use",
      "usual",
      "various",
      "verb",
      "very",
      "visit",
      "want",
      "was",
      "we",
      "well",
      "went",
      "were",
      "what",
      "when",
      "where",
      "whether",
      "which",
      "while",
      "white",
      "who",
      "whom",
      "whose",
      "why",
      "will",
      "with",
      "within",
      "without",
      "would",
      "yes",
      "yet",
      "you",
      "young",
      "your",
      "br",
      "img",
      "p",
      "lt",
      "gt",
      "quot",
      "copy"
    );
    //create an array out of the site contents
    $s      = split(" ", $this->contents);
    //initialize array
    $k      = array();
    //iterate inside the array
    foreach ($s as $key => $val) {
      //delete single or two letter words and
      //Add it to the list if the word is not
      //contained in the common words list.
      if (mb_strlen(trim($val)) >= $this->wordLengthMin && !in_array(trim($val), $common) && !is_numeric(trim($val))) {
        $k[] = trim($val);
      } //mb_strlen(trim($val)) >= $this->wordLengthMin && !in_array(trim($val), $common) && !is_numeric(trim($val))
    } //$s as $key => $val
    //count the words
    $k              = array_count_values($k);
    //sort the words from
    //highest count to the
    //lowest.
    $occur_filtered = $this->occure_filter($k, $this->wordOccuredMin);
    arsort($occur_filtered);
    $imploded = $this->implode(", ", $occur_filtered);
    //release unused variables
    unset($k);
    unset($s);
    return $imploded;
  }
  function parse_2words()
  {
    //create an array out of the site contents
    $x = split(" ", $this->contents);
    //initilize array
    //$y = array();
    for ($i = 0; $i < count($x) - 1; $i++) {
      //delete phrases lesser than 5 characters
      if ((mb_strlen(trim($x[$i])) >= $this->word2WordPhraseLengthMin) && (mb_strlen(trim($x[$i + 1])) >= $this->word2WordPhraseLengthMin)) {
        $y[] = trim($x[$i]) . " " . trim($x[$i + 1]);
      } //(mb_strlen(trim($x[$i])) >= $this->word2WordPhraseLengthMin) && (mb_strlen(trim($x[$i + 1])) >= $this->word2WordPhraseLengthMin)
    } //$i = 0; $i < count($x) - 1; $i++
    //count the 2 word phrases
    $y              = @array_count_values($y);
    $occur_filtered = $this->occure_filter($y, $this->phrase2WordLengthMinOccur);
    //sort the words from highest count to the lowest.
    @arsort($occur_filtered);
    $imploded = $this->implode(", ", $occur_filtered);
    //release unused variables
    unset($y);
    unset($x);
    return $imploded;
  }
  function parse_3words()
  {
    //create an array out of the site contents
    $a = split(" ", $this->contents);
    //initilize array
    $b = array();
    for ($i = 0; $i < count($a) - 2; $i++) {
      //delete phrases lesser than 5 characters
      if ((mb_strlen(trim($a[$i])) >= $this->word3WordPhraseLengthMin) && (mb_strlen(trim($a[$i + 1])) > $this->word3WordPhraseLengthMin) && (mb_strlen(trim($a[$i + 2])) > $this->word3WordPhraseLengthMin) && (mb_strlen(trim($a[$i]) . trim($a[$i + 1]) . trim($a[$i + 2])) > $this->phrase3WordLengthMin)) {
        $b[] = trim($a[$i]) . " " . trim($a[$i + 1]) . " " . trim($a[$i + 2]);
      } //(mb_strlen(trim($a[$i])) >= $this->word3WordPhraseLengthMin) && (mb_strlen(trim($a[$i + 1])) > $this->word3WordPhraseLengthMin) && (mb_strlen(trim($a[$i + 2])) > $this->word3WordPhraseLengthMin) && (mb_strlen(trim($a[$i]) . trim($a[$i + 1]) . trim($a[$i + 2])) > $this->phrase3WordLengthMin)
    } //$i = 0; $i < count($a) - 2; $i++
    //count the 3 word phrases
    $b              = array_count_values($b);
    //sort the words from
    //highest count to the
    //lowest.
    $occur_filtered = $this->occure_filter($b, $this->phrase3WordLengthMinOccur);
    arsort($occur_filtered);
    $imploded = $this->implode(", ", $occur_filtered);
    //release unused variables
    unset($a);
    unset($b);
    return $imploded;
  }
  function occure_filter($array_count_values, $min_occur)
  {
    if (isset($array_count_values)) {
      $occur_filtered = @array();
      foreach ($array_count_values as $word => $occured) {
        if ($occured >= $min_occur) {
          $occur_filtered[$word] = $occured;
        } //$occured >= $min_occur
      } //$array_count_values as $word => $occured
    } //isset($array_count_values)
    return $occur_filtered;
  }
  function implode($gule, $array)
  {
    if (isset($array)) {
      $c = "";
      foreach ($array as $key => $val) {
        @$c .= $key . $gule;
      } //$array as $key => $val
    } //isset($array)
    return $c;
  }
}
/**
 * Image Resizer. 
 * @author : Harish Chauhan
 * @copyright : Freeware
 * About :This PHP script will resize the given image and can show on the fly or save as image file.
 *
 */
define("HAR_AUTO_NAME", 1);
Class RESIZEIMAGE
{
  var $imgFile = "";
  var $imgWidth = 0;
  var $imgHeight = 0;
  var $imgType = "";
  var $imgAttr = "";
  var $type = NULL;
  var $_img = NULL;
  var $_error = "";
  /**
   * Constructor
   *
   * @param [String $imgFile] Image File Name
   * @return RESIZEIMAGE (Class Object)
   */
  function RESIZEIMAGE($imgFile = "")
  {
    if (!function_exists("imagecreate")) {
      $this->_error = "Error: GD Library is not available.";
      return false;
    } //!function_exists("imagecreate")
    $this->type = Array(
      1 => 'GIF',
      2 => 'JPG',
      3 => 'PNG',
      4 => 'SWF',
      5 => 'PSD',
      6 => 'BMP',
      7 => 'TIFF',
      8 => 'TIFF',
      9 => 'JPC',
      10 => 'JP2',
      11 => 'JPX',
      12 => 'JB2',
      13 => 'SWC',
      14 => 'IFF',
      15 => 'WBMP',
      16 => 'XBM'
    );
    if (!empty($imgFile))
      $this->setImage($imgFile);
  }
  /**
   * Error occured while resizing the image.
   *
   * @return String 
   */
  function error()
  {
    return $this->_error;
  }
  /**
   * Set image file name
   *
   * @param String $imgFile
   * @return void
   */
  function setImage($imgFile)
  {
    $this->imgFile = $imgFile;
    return $this->_createImage();
  }
  /**
   * 
   * @return void
   */
  function close()
  {
    return @imagedestroy($this->_img);
  }
  /**
   * Resize a image to given width and height and keep it's current width and height ratio
   * 
   * @param Number $imgwidth
   * @param Numnber $imgheight
   * @param String $newfile
   */
  function resize_limitwh($imgwidth, $imgheight, $newfile = NULL)
  {
    list($width, $height, $type, $attr) = @getimagesize($this->imgFile);
    if ($width > $imgwidth)
      $image_per = floor(($imgwidth * 100) / $width);
    if (floor(($height * $image_per) / 100) > $imgheight)
      $image_per = floor(($imgheight * 100) / $height);
    $this->resize_percentage($image_per, $newfile);
  }
  /**
   * Resize an image to given percentage.
   *
   * @param Number $percent
   * @param String $newfile
   * @return Boolean
   */
  function resize_percentage($percent = 100, $newfile = NULL)
  {
    $newWidth  = ($this->imgWidth * $percent) / 100;
    $newHeight = ($this->imgHeight * $percent) / 100;
    return $this->resize($newWidth, $newHeight, $newfile);
  }
  /**
   * Resize an image to given X and Y percentage.
   *
   * @param Number $xpercent
   * @param Number $ypercent
   * @param String $newfile
   * @return Boolean
   */
  function resize_xypercentage($xpercent = 100, $ypercent = 100, $newfile = NULL)
  {
    $newWidth  = ($this->imgWidth * $xpercent) / 100;
    $newHeight = ($this->imgHeight * $ypercent) / 100;
    return $this->resize($newWidth, $newHeight, $newfile);
  }
  /**
   * Resize an image to given width and height
   *
   * @param Number $width
   * @param Number $height
   * @param String $newfile
   * @return Boolean
   */
  function resize($width, $height, $newfile = NULL)
  {
    if (empty($this->imgFile)) {
      $this->_error = "File name is not initialised.";
      return false;
    } //empty($this->imgFile)
    if ($this->imgWidth <= 0 || $this->imgHeight <= 0) {
      $this->_error = "Could not resize given image";
      return false;
    } //$this->imgWidth <= 0 || $this->imgHeight <= 0
    if ($width <= 0)
      $width = $this->imgWidth;
    if ($height <= 0)
      $height = $this->imgHeight;
    return $this->_resize($width, $height, $newfile);
  }
  /**
   * Get the image attributes
   * @access Private
   * 		
   */
  function _getImageInfo()
  {
    @list($this->imgWidth, $this->imgHeight, $type, $this->imgAttr) = @getimagesize($this->imgFile);
    $this->imgType = $this->type[$type];
  }
  /**
   * Create the image resource 
   * @access Private
   * @return Boolean
   */
  function _createImage()
  {
    $this->_getImageInfo($imgFile);
    if ($this->imgType == 'GIF') {
      $this->_img = @imagecreatefromgif($this->imgFile);
    } //$this->imgType == 'GIF'
    elseif ($this->imgType == 'JPG') {
      $this->_img = @imagecreatefromjpeg($this->imgFile);
    } //$this->imgType == 'JPG'
      elseif ($this->imgType == 'PNG') {
      $this->_img = @imagecreatefrompng($this->imgFile);
    } //$this->imgType == 'PNG'
    if (!$this->_img || !@is_resource($this->_img)) {
      $this->_error = "Error loading " . $this->imgFile;
      return false;
    } //!$this->_img || !@is_resource($this->_img)
    return true;
  }
  /**
   * Function is used to resize the image
   * 
   * @access Private
   * @param Number $width
   * @param Number $height
   * @param String $newfile
   * @return Boolean
   */
  function _resize($width, $height, $newfile = NULL)
  {
    if (!function_exists("imagecreate")) {
      $this->_error = "Error: GD Library is not available.";
      return false;
    } //!function_exists("imagecreate")
    $newimg = @imagecreatetruecolor($width, $height);
    @imagecopyresampled($newimg, $this->_img, 0, 0, 0, 0, $width, $height, $this->imgWidth, $this->imgHeight);
    if ($newfile === HAR_AUTO_NAME) {
      if (@preg_match("/\..*+$/", @basename($this->imgFile), $matches))
        $newfile = @substr_replace($this->imgFile, "_har", -@strlen($matches[0]), 0);
    } //$newfile === HAR_AUTO_NAME
    elseif (!empty($newfile)) {
      if (!@preg_match("/\..*+$/", @basename($newfile))) {
        if (@preg_match("/\..*+$/", @basename($this->imgFile), $matches))
          $newfile = $newfile . $matches[0];
      } //!@preg_match("/\..*+$/", @basename($newfile))
    } //!empty($newfile)
    if ($this->imgType == 'GIF') {
      if (!empty($newfile))
        @imagegif($newimg, $newfile);
      else {
        @header("Content-type: image/gif");
        @imagegif($newimg);
      }
    } //$this->imgType == 'GIF'
    elseif ($this->imgType == 'JPG') {
      $notEmpty = !empty($newfile);
      if ($notEmpty)
        @imagejpeg($newimg, $newfile);
      else {
        @header("Content-type: image/jpeg");
        @imagejpeg($newimg);
      }
    } //$this->imgType == 'JPG'
      elseif ($this->imgType == 'PNG') {
      if (!empty($newfile))
        @imagepng($newimg, $newfile);
      else {
        @header("Content-type: image/png");
        @imagepng($newimg);
      }
    } //$this->imgType == 'PNG'
    @imagedestroy($newimg);
  }
}

function random_num($n = 5)
{
  return rand(0, pow(10, $n));
}

/*
 *	This script is an extensions of original libMail by Leo West
 *
 *	Note by Setec Astronomy
 *
 *	I decided to modify and republish this script because I think it's a
 *	great code! I have made some improvements like ReturnPath, a best
 *	management of To, CC, BCC, Attachment and AntiSpamming headers.
 *
 *	Original script by Leo West - west_leo@yahoo.com
 *	Original URL: http://lwest.free.fr/doc/php/lib/Mail/
 *	Original Lastmod : Nov 2001
 *	Original Version : 1.3
 *
 *	Modified by Setec Astronomy - setec@freemail.it
 *	Modified URL : http://digilander.iol.it/setecastronomy/
 *	Modified Lastmod : Sep 2004
 *	Modified Version : 1.4.1
 *
 *	Credits
 *	Thanks to:
 *   Andrea - andreamarchetto [at] hotmail [dot] com for
 * 	a small bugfix on line 342 (fopen rb windows/apache compatibility)
 *   Gian Leonardo Solazzi - iw2nke [at] yahoo [dot] it for
 *   a bugfix in To method.
 *
 *	This script is distributed  under the GPL License
 *
 *	This program is distributed in the hope that it will be useful,
 *	but WITHOUT ANY WARRANTY; without even the implied warranty of
 *	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * 	GNU General Public License for more details.
 *
 *	http://www.gnu.org/licenses/gpl.txt
 *
 */
if (stristr(PHP_OS, 'WIN')) {
  // Win 
  ini_set("sendmail_from", 'admin@somting.com');
} else { 
  // Other 

}
class Mail
{
  var $sendtoex = array();
  var $sendto = array();
  var $acc = array();
  var $abcc = array();
  var $aattach = array();
  var $fattach = array();
  var $xheaders = array();
  var $priorities = array('1 (Highest)', '2 (High)', '3 (Normal)', '4 (Low)', '5 (Lowest)');
  var $charset = "us-ascii";
  var $ctencoding = "7bit";
  var $boundary;
  var $receipt = 0;
  function Mail()
  {
    $this->boundary = "--" . md5(uniqid("myboundary"));
  }
  function Subject($subject = "")
  {
    $this->xheaders['Subject'] = strtr($subject, "\r\n", "  ");
    return true;
  }
  function From($from_email, $from_name = "")
  {
    if (!is_string($from_email)) {
      return false;
    } //!is_string($from_email)
    if (empty($from_name)) {
      $this->xheaders['From'] = $from_email;
    } //empty($from_name)
    else {
      $this->xheaders['From'] = "\"$from_name\" <$from_email>";
    }
    return true;
  }
  function ReplyTo($replyto_email, $replyto_name = "")
  {
    if (!is_string($replyto_email)) {
      return false;
    } //!is_string($replyto_email)
    if (empty($replyto_email)) {
      $this->xheaders['Reply-To'] = $replyto_email;
    } //empty($replyto_email)
    else {
      $this->xheaders['Reply-To'] = "\"$replyto_name\" <$replyto_email>";
    }
    return true;
  }
  function ReturnPath($returnpath_email, $returnpath_name = "")
  {
    if (!is_string($returnpath_email)) {
      return false;
    } //!is_string($returnpath_email)
    if (empty($returnpath_email)) {
      $this->xheaders['Return-Path'] = $returnpath_email;
    } //empty($returnpath_email)
    else {
      $this->xheaders['Return-Path'] = "\"$returnpath_name\" <$returnpath_email>";
    }
    return true;
  }
  function Receipt()
  {
    $this->receipt = 1;
    return true;
  }
  function To($address)
  {
    if (is_array($address)) {
      $this->sendto   = array();
      $this->sendtoex = array();
      foreach ($address as $key => $value) {
        if (is_numeric($key)) {
          $this->sendto[]   = $value;
          $this->sendtoex[] = $value;
        } //is_numeric($key)
        elseif (is_string($key) && is_string($value)) {
          $value            = trim(str_replace('"', '', $value));
          $this->sendto[]   = $key;
          $this->sendtoex[] = "\"$value\" <$key>";
        } //is_string($key) && is_string($value)
      } //$address as $key => $value
    } //is_array($address)
    else {
      $this->sendto[]   = $address;
      $this->sendtoex[] = $address;
    }
    return true;
  }
  function Cc($address)
  {
    if (is_array($address)) {
      $this->acc = array();
      foreach ($address as $key => $value) {
        if (is_numeric($key)) {
          $this->acc[] = $value;
        } //is_numeric($key)
        elseif (is_string($key) && is_string($value)) {
          $value       = str_replace('"', '', $value);
          $this->acc[] = "\"$value\" <$key>";
        } //is_string($key) && is_string($value)
      } //$address as $key => $value
    } //is_array($address)
    else {
      $this->acc = array(
        $address
      );
    }
    return true;
  }
  function Bcc($address)
  {
    if (is_array($address)) {
      $this->abcc = array();
      foreach ($address as $key => $value) {
        if (is_numeric($key)) {
          $this->abcc[] = $value;
        } //is_numeric($key)
        elseif (is_string($key) && is_string($value)) {
          $value        = str_replace('"', '', $value);
          $this->abcc[] = "\"$value\" <$key>";
        } //is_string($key) && is_string($value)
      } //$address as $key => $value
    } //is_array($address)
    else {
      $this->abcc = array(
        $address
      );
    }
    return true;
  }
  function Body($body = "", $charset = "")
  {
    $this->body = $body;
    if (!empty($charset)) {
      $this->charset = strtolower($charset);
      if ($this->charset != "us-ascii") {
        $this->ctencoding = "8bit";
      } //$this->charset != "us-ascii"
    } //!empty($charset)
    return true;
  }
  function Organization($org = "")
  {
    if (!empty($org)) {
      $this->xheaders['Organization'] = $org;
    } //!empty($org)
    return true;
  }
  function AntiSpaming($client_ip = "", $proxy_server = "", $user_agent = "")
  {
    if (empty($client_ip)) {
      if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        $client_ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
      } //isset($_SERVER['HTTP_X_FORWARDED_FOR'])
      elseif (isset($_SERVER['HTTP_CLIENT_IP'])) {
        $client_ip = $_SERVER['HTTP_CLIENT_IP'];
      } //isset($_SERVER['HTTP_CLIENT_IP'])
        elseif (isset($_SERVER['HTTP_FROM '])) {
        $client_ip = $_SERVER['HTTP_FROM'];
      } //isset($_SERVER['HTTP_FROM '])
        elseif (isset($_SERVER['REMOTE_ADDR'])) {
        $client_ip = $_SERVER['REMOTE_ADDR'];
      } //isset($_SERVER['REMOTE_ADDR'])
      $this->xheaders['X-HTTP-Posting-Host'] = $client_ip;
    } //empty($client_ip)
    else {
      $this->xheaders['X-HTTP-Posting-Host'] = $client_ip;
    }
    if (empty($proxy_server)) {
      if ($client_ip != $_SERVER['REMOTE_ADDR']) {
        $this->xheaders['X-HTTP-Proxy-Server'] = $_SERVER['REMOTE_ADDR'];
      } //$client_ip != $_SERVER['REMOTE_ADDR']
    } //empty($proxy_server)
    else {
      $this->xheaders['X-HTTP-Proxy-Server'] = $proxy_server;
    }
    if (empty($user_agent)) {
      if (isset($_SERVER['HTTP_USER_AGENT'])) {
        $this->xheaders['X-HTTP-Posting-UserAgent'] = $_SERVER['HTTP_USER_AGENT'];
      } //isset($_SERVER['HTTP_USER_AGENT'])
      else {
        $this->xheaders['X-HTTP-Posting-UserAgent'] = "Unknown";
      }
    } //empty($user_agent)
    else {
      $this->xheaders['X-HTTP-Posting-UserAgent'] = $user_agent;
    }
    return true;
  }
  function Priority($priority = 3)
  {
    if (!isset($this->priorities[$priority - 1])) {
      return false;
    } //!isset($this->priorities[$priority - 1])
    $this->xheaders["X-Priority"] = $this->priorities[$priority - 1];
    return true;
  }
  function Attach($filepath, $mimetype = "", $disposition = "inline", $filename = "")
  {
    if (empty($filepath)) {
      return false;
    } //empty($filepath)
    if (empty($mimetype)) {
      $mimetype = "application/x-unknown-content-type";
    } //empty($mimetype)
    if (empty($filename)) {
      $filename = basename($filepath);
    } //empty($filename)
    $this->fattach[] = $filename;
    $this->aattach[] = $filepath;
    $this->actype[]  = $mimetype;
    $this->adispo[]  = $disposition;
    return true;
  }
  function BuildMail()
  {
    $this->headers = "";
    if (count($this->sendtoex) > 0) {
      $this->xheaders['To'] = implode(", ", $this->sendtoex);
    } //count($this->sendtoex) > 0
    if (count($this->acc) > 0) {
      $this->xheaders['CC'] = implode(", ", $this->acc);
    } //count($this->acc) > 0
    if (count($this->abcc) > 0) {
      $this->xheaders['BCC'] = implode(", ", $this->abcc);
    } //count($this->abcc) > 0
    if ($this->receipt) {
      if (isset($this->xheaders["Reply-To"])) {
        $this->xheaders["Disposition-Notification-To"] = $this->xheaders["Reply-To"];
      } //isset($this->xheaders["Reply-To"])
      else {
        $this->xheaders["Disposition-Notification-To"] = $this->xheaders['From'];
      }
    } //$this->receipt
    if ($this->charset != "") {
      $this->xheaders["Mime-Version"]              = "1.0";
      $this->xheaders["Content-Type"]              = "text/html; charset=$this->charset";
      $this->xheaders["Content-Transfer-Encoding"] = $this->ctencoding;
    } //$this->charset != ""
    $this->xheaders["X-Mailer"] = "Php/libMailv2.1";
    if (count($this->aattach) > 0) {
      $this->_build_attachement();
    } //count($this->aattach) > 0
    else {
      $this->fullBody = $this->body;
    }
    reset($this->xheaders);
    while (list($hdr, $value) = each($this->xheaders)) {
      if ($hdr != "Subject") {
        $this->headers .= "$hdr: $value\n";
      } //$hdr != "Subject"
    } //list($hdr, $value) = each($this->xheaders)
    return true;
  }
  
  function Send()
  {
    $this->BuildMail();
    $strTo = implode(", ", $this->sendto);
    return mail($strTo, $this->xheaders['Subject'], $this->fullBody, $this->headers);
  }
  function Get()
  {
    $this->BuildMail();
    $mail = $this->headers . "\n";
    $mail .= $this->fullBody;
    return $mail;
  }
  function _build_attachement()
  {
    $this->xheaders["Content-Type"] = "multipart/mixed;\n boundary=\"$this->boundary\"";
    $this->fullBody                 = "This is a multi-part message in MIME format.\n--$this->boundary\n";
    $this->fullBody .= "Content-Type: text/html; charset=$this->charset\nContent-Transfer-Encoding: $this->ctencoding\n\n" . $this->body . "\n";
    $sep = chr(13) . chr(10);
    $ata = array();
    $k   = 0;
    for ($i = 0; $i < count($this->aattach); $i++) {
      $filename    = $this->aattach[$i];
      $basename    = basename($this->fattach[$i]);
      $ctype       = $this->actype[$i]; // content-type
      $disposition = $this->adispo[$i];
      if (!file_exists($filename)) {
        return false;
      } //!file_exists($filename)
      $subhdr    = "--$this->boundary\nContent-type: $ctype;\n name=\"$basename\"\nContent-Transfer-Encoding: base64\nContent-Disposition: $disposition;\n  filename=\"$basename\"\n";
      $ata[$k++] = $subhdr;
      $linesz    = filesize($filename) + 1;
      $fp        = fopen($filename, 'rb');
      $ata[$k++] = chunk_split(base64_encode(fread($fp, $linesz)));
      fclose($fp);
    } //$i = 0; $i < count($this->aattach); $i++
    $this->fullBody .= implode($sep, $ata);
  }
  
  
  
function Mail_Password_Generator()
  {
	$string1="abcdefghijklmnopqrstuvwxyz";
	$string2="ABCDEFGHIJKLMNOPQRSTUVWXYZ";
	$string3="1234567890";
	$string4="!@#$%^&*()_+{}.?~";
	
	$string=$string1.$string2.$string3.$string4;
	$string= str_shuffle($string);
	
	$pass=substr($string,0,10);
	$pass_array[0]=$pass;
	
	$new_pass= md5($pass);
	$pass_array[1]=$new_pass;
	return $pass_array;
  }  
} // class Mail

function converttime($hour)
{
  $piece   = explode(":", $hour);
  $hour    = $piece['0'];
  $minutes = $piece['1'];
  return (($hour % 12) ? $hour % 12 : 12) . ':' . $minutes . ' ' . (($hour > 12) ? 'PM' : 'AM');
}

	function getUserAuthorizationsInRestaurant(){
		global $database;
  		
  		$query = "select name, value as activity from options where name like '%_authorized' and rid = '".$_SESSION['arid']."'";
  		$results = $database->select($query);
  		$users = Array();
  		
  		if(is_array($results)){
  			foreach ($results as $option){
  				$email = explode("_authorized", $option['name']);
    			$email = $email[0];
    			$activity = $option['activity'];

    			if (!isset($users['email'])){
      			$users[$email]['email'] = $email;
    			}
    		
    			$users[$email]['authorized'][$activity]="checked";
  			}
  		}

  		return $users; 
	}

function getDiscountAmount($orderAmount, $discount, $discountType, $discountMinimum){

  if ($orderAmount <= $discountMinimum) {
    return 0;
  }

  if ($discountType == 'percent') {
    $discount = $discount / 100;
    $amount = $orderAmount * $discount;

  } else {
    $amount = $discount;
  }
  return $amount;
}

?>
